package Utils;

import Client.Client;
import GUI.showMessageFrame;
import Monitor.ClientThread;
import org.json.JSONObject;

import javax.swing.*;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Timer;
import java.util.TimerTask;

import static java.lang.System.exit;
import static java.lang.Thread.sleep;

/**
 * The type Packet utils.
 *
 * @author dzr
 * @version 1.0
 */
public class PacketUtils {
    /**
     * The constant client's socket.
     */
    public static DatagramSocket client;

    /**
     * Send packet and change into json.
     *
     * @param jsonObject the json object
     */
    public static void sendPacket(JSONObject jsonObject){
        byte[] data = jsonObject.toString().getBytes();
        DatagramPacket packet = new DatagramPacket(data, data.length, Client.server);
        try {
            client.send(packet);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Receive packet and change into json.
     *
     * @return the json object
     */
    public static JSONObject receivePacket(){
        Timer t = new Timer();
        byte[] ret_data = new byte[2048];
        DatagramPacket packet = new DatagramPacket(ret_data, ret_data.length);
        try {
            t.schedule(new TimerTask() {
                @Override
                public void run() {
                    System.out.println("网络连接断开或者服务器关闭，程序退出");
                    exit(-1);
                }
            }, 3000);
            client.receive(packet);
        } catch (IOException e) {
            e.printStackTrace();
        }
        t.cancel();
        String ret_msg = new String(ret_data, 0, packet.getLength());
        return new JSONObject(ret_msg);
    }
}
